<template>
  <div class="clipping-page-container">
    <!-- 头部操作栏 -->
    <HeaderActions
      @navigateBack="handleBackToList"
      @submitClip="handleStartClipping"
      :submitting="false"
    />
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 播放器和信息区域 -->
      <div class="player-container">
        <!-- 视频播放器区域 -->
        <VideoPlayerSection
          :src="videoUrl"
          :isPlaying="isPlaying"
          @ready="onPlayerReady"
          @timeupdate="onTimeUpdate"
          @error="onPlayerError"
          @togglePlay="handleTogglePlay"
          @stepForward="handleStepForward"
          @stepBackward="handleStepBackward"
          @forward="handleForward"
          @rewind="handleRewind"
        />
        
        <!-- 侧边信息区域 -->
        <SideInfoSection
          :recording="recordingInfo"
          :clippingRecords="clippingRecords"
          @previewClip="handlePreviewClip"
          @editRecord="handleEditRecord"
          @deleteRecord="handleDeleteRecord"
        />
      </div>
      
      <!-- 时间轴控制区域 -->
      <TimelineSection
        :totalDuration="totalDuration"
        :currentTime="currentTime"
        @confirmClipping="handleConfirmClipping"
        @setStartTime="handleSetStartTime"
        @setEndTime="handleSetEndTime"
        @resetTimeRange="handleResetTimeRange"
        @fitToScreen="handleFitToScreen"
      />
    </div>
    
    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="拆条预览"
      width="80%"
      :destroy-on-close="true"
    >
      <div class="preview-content">
        <div v-if="previewVideoUrl" class="preview-video-wrapper">
          <VideoPlayer
            :src="previewVideoUrl"
            :autoplay="true"
            :controls="true"
            style="width: 100%; height: 400px;"
          />
        </div>
        <div v-else class="preview-loading">
          <el-icon><Loading /></el-icon>
          <span>加载预览视频中...</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import HeaderActions from './HeaderActions.vue'
import VideoPlayerSection from './VideoPlayerSection.vue'
import SideInfoSection from './SideInfoSection.vue'
import TimelineSection from './TimelineSection.vue'

// 页面状态
const videoUrl = ref('')
const isPlaying = ref(false)
const currentTime = ref(0)
const totalDuration = ref(0)
const recordingInfo = ref(null)
const clippingRecords = ref([])
const previewDialogVisible = ref(false)
const previewVideoUrl = ref('')

// 模拟数据加载
const loadMockData = () => {
  // 使用支持CORS的公共视频URL作为模拟数据
  videoUrl.value = 'https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4'
  
  // 模拟录制信息
  recordingInfo.value = {
    id: 1,
    recording_url: 'https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4',
    resolution: '1920x1080',
    bitrate: '2500Kbps',
    duration: 3600,
    size: 1073741824 // 1GB
  }
  
  // 设置总时长
  totalDuration.value = recordingInfo.value.duration
  
  // 模拟拆条记录
  clippingRecords.value = [
    {
      id: 101,
      name: '开场片段',
      startTime: '00:00:00',
      endTime: '00:01:30',
      duration: '01:30',
      url: 'https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4'
    },
    {
      id: 102,
      name: '重要讲话',
      startTime: '00:15:30',
      endTime: '00:18:45',
      duration: '03:15',
      url: 'https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4'
    },
    {
      id: 103,
      name: '精彩互动',
      startTime: '00:45:12',
      endTime: '00:45:22',
      duration: '00:10',
      url: 'https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4'
    }
  ]
}

// 播放器事件处理
const onPlayerReady = (event) => {
  console.log('Player is ready', event)
  // 可以在这里初始化播放器的额外设置
}

const onTimeUpdate = (event) => {
  // 更新当前时间
  if (event && event.target) {
    currentTime.value = event.target.currentTime
  }
}

const onPlayerError = (event) => {
  console.error('Player error:', event)
  ElMessage.error('视频播放出错，请稍后再试')
}

// 控制方法
const handleTogglePlay = () => {
  isPlaying.value = !isPlaying.value
  // 这里应该调用实际的播放/暂停逻辑
}

const handleStepForward = () => {
  // 前进一帧
  currentTime.value += 0.04 // 假设25fps
}

const handleStepBackward = () => {
  // 后退一帧
  currentTime.value = Math.max(0, currentTime.value - 0.04)
}

const handleForward = () => {
  // 快进
  currentTime.value = Math.min(totalDuration.value, currentTime.value + 5)
}

const handleRewind = () => {
  // 快退
  currentTime.value = Math.max(0, currentTime.value - 5)
}

// 头部操作栏事件
const handleBackToList = () => {
  // 返回列表页面
  console.log('Back to list')
  // 实际应用中应该使用router跳转
  // router.push('/recordings')
}

const handleStartClipping = () => {
  // 开始拆条流程
  console.log('Start clipping process')
}

// 侧边信息区域事件
const handlePreviewClip = (clip) => {
  // 预览拆条视频
  previewVideoUrl.value = clip.url
  previewDialogVisible.value = true
}

const handleEditRecord = (record) => {
  // 编辑拆条记录
  console.log('Edit record:', record)
}

const handleDeleteRecord = (id) => {
  // 删除拆条记录
  ElMessageBox.confirm(
    '确定要删除这条拆条记录吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    clippingRecords.value = clippingRecords.value.filter(item => item.id !== id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消操作
  })
}

// 时间轴控制事件
const handleConfirmClipping = (timeRange) => {
  // 确认拆条
  console.log('Confirm clipping with time range:', timeRange)
  // 实际应用中应该调用API进行拆条操作
  ElMessage.success('拆条任务已提交，正在处理...')
}

const handleSetStartTime = (time) => {
  // 设置开始时间
  console.log('Set start time:', time)
}

const handleSetEndTime = (time) => {
  // 设置结束时间
  console.log('Set end time:', time)
}

const handleResetTimeRange = () => {
  // 重置时间范围
  console.log('Reset time range')
}

const handleFitToScreen = () => {
  // 适配屏幕
  console.log('Fit to screen')
}

// 生命周期
onMounted(() => {
  loadMockData()
})
</script>

<style scoped>
.clipping-page-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color);
  overflow: hidden;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 12px;
  gap: 12px;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
}

.player-container {
  flex: 1;
  display: flex;
  gap: 12px;
  min-height: 0;
  width: 100%;
  box-sizing: border-box;
}

.preview-content {
  padding: 12px;
}

.preview-video-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: var(--text-secondary-color);
}

.preview-loading .el-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

@media (max-width: 992px) {
  .player-container {
    flex-direction: column;
  }
  
  .main-content {
    padding: 8px;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .clipping-page-container {
    height: 100vh;
  }
  
  .preview-content {
    padding: 8px;
  }
}
</style>